<script setup>
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import websocket from '@/utils/websocket'
import { useMyInfoQuery } from '@/composables/useUserInfoQuery'

const props = defineProps({
  visible: Boolean,
  userInfo: Object,
})
const emit = defineEmits(['update:visible', 'success'])

const { userInfo: myInfo } = useMyInfoQuery()

const friendRemark = ref('')

watch(() => props.visible, (val) => {
  if (val) friendRemark.value = ''
})

function handleClose() {
  emit('update:visible', false)
}

function submitAddFriend() {
  if (!friendRemark.value.trim()) {
    ElMessage.error('备注不能为空')
    return
  }
  if (friendRemark.value.length > 20) {
    ElMessage.error('备注不能超过20字')
    return
  }
  if (!myInfo.value || !myInfo.value.result || !myInfo.value.result.uid) {
    ElMessage.error('请先登录')
    return
  }
  const loginUser = myInfo.value.result
  const msg = {
    type: 'person-apply',
    data: {
      senderId: loginUser.uid,
      senderName: loginUser.username,
      senderAvatar: loginUser.avatar,
      receiverId: props.userInfo.uid,
      notation: friendRemark.value.trim(),
      applyMessage: `你好,我是${loginUser.username}`
    }
  }
  websocket.sendMessage(msg)
  ElMessage.success('申请已发送')
  emit('success')
  handleClose()
}
</script>

<template>
  <el-dialog :model-value="visible" title="申请加好友" width="350px" @close="handleClose" @update:model-value="emit('update:visible', $event)">
    <el-form @submit.prevent>
      <el-form-item label="备注">
        <el-input v-model="friendRemark" maxlength="20" show-word-limit placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="submitAddFriend">提交</el-button>
    </template>
  </el-dialog>
</template> 